package org.tiger.netty.server.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author lwl
 * @date 2020/9/25 17:16
 */
public class NioStudyOne {

	private static Logger logger = LoggerFactory.getLogger(NioStudyOne.class);

	public static void main(String[] args) {
		try {
			readAndWrite();
		} catch (Exception e) {
			logger.error("********", e);
		}

	}

	public static void readAndWrite() throws Exception {

		String path = NioStudyOne.class.getClassLoader().getResource("").getPath().toString();
		logger.info("path : " + path);
		File fileIn = new File(path + "oneRead.txt");
		File fileOut = new File(path + "oneWrite.txt");
		FileInputStream fileInputStream = new FileInputStream(fileIn);
		FileOutputStream fileOutputStream = new FileOutputStream(fileOut);
		//ByteBuffer byteBuffer = ByteBuffer.allocate(64);
		//直接内存
		ByteBuffer byteBuffer = ByteBuffer.allocateDirect(64);

		FileChannel fileChannelInput = fileInputStream.getChannel();
		FileChannel fileChannelOutput = fileOutputStream.getChannel();

		while (true) {
			byteBuffer.clear();
			int read = fileChannelInput.read(byteBuffer);
			if (read == -1) {
				break;
			}
			byteBuffer.flip();
			fileChannelOutput.write(byteBuffer);
		}
		fileInputStream.close();
		fileOutputStream.close();
	}

}
